package servlets.loginServlets;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import structures.User;
import twitter4j.internal.org.json.JSONObject;

public class AddSocialLoginServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2629813193821013212L;
	private static final String URLBASE = "http://localhost:8080/ISellToYouRESTWebService/AddSocialLogin";
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response){
		String idUser, idSocial, social, answer, inputLine, error;
		JSONObject answerJson;
		BufferedReader reader;
		StringBuffer responseBuffer;
		User user;
		idUser = request.getParameter("idUser");
		idSocial = request.getParameter("idSocial");
		social = request.getParameter("social");
		
		try {
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(URLBASE + "?idUser="+ idUser + "&idSocial="+ idSocial + "&social="+ social).openConnection();
			httpConnection.setRequestMethod("PUT");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();

			 
			
			answer = responseBuffer.toString();
			
			
			
			if(answer.equals("null"))
				throw new Exception();
			
			answerJson = new JSONObject(answer);
			if (answerJson.has("errors")){
				error = answerJson.getString("errors");
				//if result = yes there are errors, if result = no there anen't errors
				request.getSession().setAttribute("error", error);
				if(error.equals("no")){
					//add the new idSocial to user
					user = (User) request.getSession().getAttribute("user");
					request.getSession().removeAttribute("user");
					switch(social){
					case "Facebook": 
						user.setIdFacebook(idSocial);
						break;
					case "Twitter": 
						user.setIdTwitter(idSocial);
						break;
					case "Google": 
						user.setIdGoogle(idSocial);
						break;
					}
					request.getSession().setAttribute("user",user);
				}
            }
			
			
			
			
			response.sendRedirect(request.getContextPath() + "/profile.jsp");
			
		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				request.getSession().setAttribute("error", "yes");
				response.sendRedirect(request.getContextPath() + "/profile.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
